package org.zjt.thread.interrupt;

import java.net.MalformedURLException;
import java.net.URL;
import java.time.LocalDateTime;
import java.util.Objects;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Description:
 *
 * @author juntao.zhang
 * Date: 2018-05-31 下午5:20
 * @see
 */
public class HttpRequest implements Runnable{

    private static final AtomicInteger ATOMIC_INTEGER = new AtomicInteger(0);

    private static final LinkedBlockingQueue<InterruptableOperation> LINKED_BLOCKING_QUEUE = new LinkedBlockingQueue();

    private Future<String> submit;

    private String body;

    private final ThreadPoolManager threadPoolManager;

    public HttpRequest(ThreadPoolManager threadPoolManager) {
        this.threadPoolManager = threadPoolManager;
    }

    public void send() throws MalformedURLException {
        BIOInterruptableOperation BIOInterruptableOperation = new BIOInterruptableOperation(LocalDateTime.now(),new URL("https://www.baidu.com"), this);
        LINKED_BLOCKING_QUEUE.add(BIOInterruptableOperation);
    }


    public void asyncSend() throws MalformedURLException {
        NIOInterruptableOperation NIOInterruptableOperation = new NIOInterruptableOperation(LocalDateTime.now(),new URL("https://www.baidu.com"), this);
        LINKED_BLOCKING_QUEUE.add(NIOInterruptableOperation);
    }

    public void complete() {
        try {
            body = submit.get();
            System.out.println(ATOMIC_INTEGER.incrementAndGet() + body);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (Boolean.TRUE){
            try {
                InterruptableOperation poll = LINKED_BLOCKING_QUEUE.take();
                if (Objects.isNull(poll))
                    continue;
                Future<String> submit = threadPoolManager.submit(poll);

                System.out.println(ATOMIC_INTEGER.incrementAndGet() + submit.get());
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (Exception e) {
                e.printStackTrace();
            }
            this.submit = submit;
        }
    }
}
